<script setup lang="ts">
import { useRoute } from 'vue-router';
import AfterMessagePop from '@/pages/afterSales/afterMessagePop.vue';
import LookVoucherPop from '@/pages/allOrder/lookVoucherPop.vue';
import { backDetailsGet, closedAfterPost, confirmPayPost, deliverPost } from '@/services/my.ts';
import type { AfterDetailData, BackGoodsList } from '@/types/my.ts';
import AfterSalePop from '@/pages/allOrder/afterSalePop.vue';

const $route = useRoute();
const detailData = reactive({
  afterDetailData: {} as AfterDetailData,
  backOrderGoodsList: [] as BackGoodsList[],
});

// 售后明细
const backHistoryList = ref([]);
const afterMessagePop = ref(false);
const onAfterMessageClick = () => {
  afterMessagePop.value = true;
};

const totalsPrice = computed(() => {
  let total = detailData.backOrderGoodsList.reduce((total: any, item: any) => {
    return total + item.backGoodsPrice * item.amount;
  }, 0);
  return total.toFixed(2);
});

const discountPrice = computed(() => {
  let disPrick = detailData.backOrderGoodsList.reduce((total: any, item: any) => {
    return total + item.backDiscountPrice * item.amount;
  }, 0);
  return disPrick.toFixed(2);
});

/* eslint-disable */
const getStatusText = (backCheck: string) => {
  switch (backCheck) {
    case 'BACK_APPLY':
      return '等待商家审核';
    case 'AGREE_BACK':
      return '商家同意退款(请根据退货信息将售后商品退回，并填写物流单号)';
    case 'REFUSE_BACK':
      return '商家拒绝售后申请';
    case 'DELIVERED':
      return '退回商品已发货';
    case 'REFUND':
      return '商家已退款';
    case 'RECEIVED':
      return '商家已收货';
    case 'CONFIRM_RECEIPT':
      return '已完成';
    case 'CANCELED':
      return '已关闭';
    default:
      return '暂无最新状态';
  }
};

const imagePreview = ref(false);
const imageList = ref<string[]>([]);
const onPreviewClick = () => {
  imageList.value = [detailData.afterDetailData.backPayProof];
  imagePreview.value = true;
};

// 查看凭证
const lookVoucherPop = ref(false);
const lookVoucherImg = ref('');
const onLookVoucherClick = () => {
  lookVoucherImg.value = detailData.afterDetailData.payProof;
  lookVoucherPop.value = true;
};

const deliverPop = ref(false);
const trackNumber = ref('');
const onUpDeliverClick = () => {
  deliverPop.value = true;
};
const onUpTrackClick = async () => {
  const { err, message } = await deliverPost({
    orderId: detailData.afterDetailData.orderId,
    trackNumber: trackNumber.value,
  });
  if (err) {
    showToast(err);
  } else {
    showToast(message);
    deliverPop.value = false;
    await loadData();
  }
};

const onConfirmPayClick = async () => {
  const { err, message } = await confirmPayPost({
    orderId: detailData.afterDetailData.orderId,
  });
  if (err) {
    showToast(err);
  } else {
    showToast(message);
    await loadData();
  }
};

const onCloseAfterClick = async () => {
  const { err, message } = await closedAfterPost({
    orderId: detailData.afterDetailData.orderId,
  });
  if (err) {
    showToast(err);
  } else {
    showToast(message);
    await loadData();
  }
};

// 售后
const afterSalePop = ref(false);
const afterOrderId = ref('');
const onChangeRequestClick = () => {
  afterSalePop.value = true;
  afterOrderId.value = detailData.afterDetailData.orderId;
};

const loadData = async () => {
  const { data, err } = await backDetailsGet({
    orderId: $route.query.orderId,
  });
  if (err) {
    showToast(err);
    return;
  }
  detailData.afterDetailData = data;
  detailData.backOrderGoodsList = data.backOrderGoodsList;
  backHistoryList.value = data.backHistoryList?.map((e: any) => {
    return {
      ...e,
      historyVal: JSON.parse(e.historyVal),
    };
  });
};
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="detail-container">
    <div class="top">
      <div class="top-icon">
        <svg-icon icon-class="shop" size="1.4em" />
        <div class="icon-status">
          {{ getStatusText(detailData.afterDetailData.backCheck) }}
        </div>
      </div>
      <div v-if="detailData.afterDetailData.backCheck === 'REFUSE_BACK'">
        <van-cell title="拒绝理由" :value="detailData.afterDetailData.refuseReason || ''" />
      </div>
      <div v-if="detailData.afterDetailData.backCheck === 'AGREE_BACK'">
        <div class="back-text">请根据退货信息将售后商品退回，并填写物流单号</div>
        <van-cell
          title="退货地址"
          :value="`${detailData.afterDetailData.backShippingAddress} ${detailData.afterDetailData.backShippingPerson} ${detailData.afterDetailData.backShippingMobile}`"
        />
      </div>
      <div v-if="detailData.afterDetailData.backCheck === 'REFUND'">
        <van-cell title="退款凭证">
          <template #value>
            <van-image @click="onPreviewClick" :src="detailData.afterDetailData.backPayProof" />
          </template>
        </van-cell>
      </div>
    </div>
    <div class="order-box">
      <div class="box-title">
        <div class="title-left">
          <div class="title-icon">
            <svg-icon icon-class="shop" size="1.3em" />
            <div class="title-text">{{ detailData.afterDetailData.supplierName }}</div>
            <svg-icon icon-class="right" size="1em" />
          </div>
          <div class="title-name">退货退款</div>
        </div>
      </div>
      <div class="goods_box" v-for="orderItem in detailData.backOrderGoodsList" :key="orderItem.id">
        <van-image :src="orderItem.goodsImg?.split(',')[0]" round />
        <div class="goods_spc">
          <div class="goods_name">{{ orderItem.goodsName }}</div>
          <div class="goods_level">{{ orderItem.goodsSpec }}</div>
        </div>
        <div class="goods_price">
          <div class="price_num curPrice">{{ `￥${orderItem.backDiscountPrice}` }}</div>
          <div class="price_num disPrice">{{ `￥${orderItem.backGoodsPrice}` }}</div>
          <div class="price_num amount">{{ `x ${orderItem.amount}` }}</div>
        </div>
      </div>
      <div class="order-price">
        <div class="total-price">
          合计金额：
          <span>{{ `￥${totalsPrice}` }}</span>
        </div>
        <div class="disPrice">
          <span>折后金额：</span>
          <span>￥</span>
          <span class="dis-icon">{{ `${discountPrice}` }}</span>
        </div>
      </div>
    </div>
    <van-field
      :model-value="detailData.afterDetailData.orderCode"
      class="custom-field"
      label="订单编号"
      type="textarea"
      rows="1"
      autosize
      readonly
    />
    <van-field
      :model-value="detailData.afterDetailData.createTime"
      class="custom-field"
      label="创建时间"
      type="textarea"
      rows="1"
      autosize
      readonly
    />
    <van-field
      :model-value="detailData.afterDetailData.backRemark"
      class="custom-field"
      label="售后原因"
      type="textarea"
      rows="1"
      autosize
      readonly
    />
  </div>

  <van-popup v-model:show="deliverPop" position="bottom" :style="{ maxHeight: '70%' }">
    <div class="deliver-pop">
      <div class="title">填写物流单号</div>
      <div class="box">
        <van-field
          v-model="trackNumber"
          rows="2"
          autosize
          type="textarea"
          placeholder="请填写物流单号"
        />
      </div>
      <van-button @click="onUpTrackClick" color="#E89000" round block text="提交" />
    </div>
  </van-popup>
  <AfterMessagePop v-model="afterMessagePop" :backHistoryList="backHistoryList" />
  <van-action-bar placeholder>
    <template #default>
      <!--
          查看凭证 全都有
          售后明细 AGREE_BACK *
          确认收款 REFUND *
          修改申请 REFUSE_BACK
          关闭售后 REFUSE_BACK *
          上传单号 AGREE_BACK *
       -->
      <div class="action-box">
        <van-button @click="onLookVoucherClick" class="colorButton" text="查看凭证" />
        <van-button @click="onAfterMessageClick" class="infoButton" text="售后明细" />
        <van-button
          v-if="detailData.afterDetailData.backCheck === 'REFUND'"
          @click="onConfirmPayClick"
          class="infoButton"
          text="确认收款"
        />
        <van-button
          v-if="detailData.afterDetailData.backCheck === 'REFUSE_BACK'"
          @click="onChangeRequestClick"
          class="infoButton"
          text="修改申请"
        />
        <van-button
          v-if="detailData.afterDetailData.backCheck === 'REFUSE_BACK'"
          @click="onCloseAfterClick"
          class="infoButton"
          text="关闭售后"
        />
        <van-button
          v-if="detailData.afterDetailData.backCheck === 'AGREE_BACK'"
          @click="onUpDeliverClick"
          class="infoButton"
          text="上传单号"
        />
      </div>
    </template>
  </van-action-bar>
  <LookVoucherPop v-model="lookVoucherPop" :look-voucher-img="lookVoucherImg" />
  <van-image-preview v-model:show="imagePreview" :images="imageList"></van-image-preview>
  <AfterSalePop v-model="afterSalePop" :order-id="afterOrderId" />
</template>

<style scoped lang="scss">
.detail-container {
  width: 100%;
  min-height: 100vh;
  background: #f6f6f6;

  .van-cell:after {
    border-bottom: none !important;
  }

  .top {
    width: 100%;
    min-height: 48px;
    font-size: 16px;
    font-weight: 500;
    padding: 0 16px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    color: #e86600;
    background: #fff;

    :deep(.van-cell) {
      min-height: 36px;
      padding: 0 8px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #f6f6f6 !important;
      margin-bottom: 16px;
    }

    :deep(.van-cell__title) {
      color: #454545;
      font-size: 13px;
      font-weight: 400;
      max-width: 100px !important;
    }

    .top-icon {
      width: 100%;
      height: 48px;
      display: flex;
      align-items: center;

      .icon-status {
        margin-left: 8px;
      }
    }

    .back-text {
      font-size: 12px;
      font-weight: 400;
      margin-bottom: 8px;
      color: #aaaaaa;
    }

    .van-image {
      margin-top: 8px;
      width: 48px;
      height: 48px;
    }
  }

  .box-title {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .title-left {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title-icon {
        display: flex;
        align-items: center;
      }

      .title-name {
        font-size: 14px;
        font-weight: 400;
        color: #e86600;
      }

      .title-text {
        font-size: 13px;
        font-weight: 500;
        margin-left: 8px;
        color: #222222;
      }
    }
  }

  .order-box {
    width: 100%;
    background: white;
    padding: 0 16px;
    margin-top: 8px;

    .goods_box {
      width: 100%;
      height: 104px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #fff;

      .van-image {
        width: 88px;
        height: 88px;
        border-radius: 8px;
      }

      .goods_spc {
        width: 170px;
        height: 100%;
        padding-top: 8px;

        .goods_name {
          width: 100%;
          font-size: 13px;
          font-weight: 500;
          color: #000000;
          // 超过一行就显示省略号
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .goods_level {
          width: 100%;
          font-size: 12px;
          font-weight: 400;
          margin-top: 3px;
          color: #787878;
          // 超过三行就显示省略号
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .goods_price {
        height: 100%;
        padding-top: 8px;

        .price_num {
          display: flex;
          justify-content: flex-end;
        }

        .curPrice {
          font-size: 14px;
          font-weight: 500;
        }

        .disPrice {
          font-size: 12px;
          font-weight: 400;
          color: #aaaaaa;
          text-decoration: line-through;
        }

        .amount {
          font-size: 10px;
          font-weight: 400;
          color: #aaaaaa;
        }
      }
    }

    .order-price {
      width: 100%;
      height: 24px;
      font-size: 12px;
      font-weight: 400;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .total-price {
        color: #787878;

        span {
          text-decoration: line-through;
        }
      }

      .disPrice {
        margin-left: 12px;
        display: flex;
        align-items: center;
        color: #222222;

        .dis-icon {
          font-size: 16px;
        }
      }
    }
  }
}

.deliver-pop {
  width: 100%;
  padding: 0 16px;

  .title {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #000000;
  }

  .van-field {
    background: #f6f6f6;
  }

  .van-button {
    height: 40px;
    margin: 86px 0 24px 0;
  }
}

:deep(.van-field__control) {
  font-size: 13px;
  font-weight: 400;
  color: #aaaaaa;
}

.action-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;

  .van-button {
    height: 36px;
    margin: 0 6px;
    padding: 0 10px;
  }

  .infoButton {
    color: #454545;
    background: #f6f6f6;
  }

  .colorButton {
    color: #e86600;
    background: #e8900033;
  }
}
</style>
